package com.example.digitclassifier3

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import com.divyanshu.draw.widget.DrawView
import com.example.digitclassifier3.ml.Mnist
import org.tensorflow.lite.DataType
import org.tensorflow.lite.support.tensorbuffer.TensorBuffer
import java.nio.ByteBuffer
import java.nio.ByteOrder
//import kotlin.coroutines.jvm.internal.CompletedContinuation.context

class MainActivity : AppCompatActivity() {
    private var drawView: DrawView? = null
    private var cleanButton:Button? = null
    private var predictedTextView:TextView? = null
    private var digitClassifier = DigitClassifier(this)

    @SuppressLint("ClickableViewAccessibility")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        drawView = findViewById(R.id.draw_view)
        drawView?.setStrokeWidth(70.0f)
        drawView?.setColor(Color.WHITE)
        drawView?.setBackgroundColor(Color.BLACK)
        //设置背景样式

        cleanButton = findViewById(R.id.clear_button)
        //设置按钮

        predictedTextView = findViewById(R.id.predicted_text)
        //设置预测结果文本框

        cleanButton?.setOnClickListener(){
            drawView?.clearCanvas()
            predictedTextView?.text = getString(R.string.prediction_text_placeholder)
        }
        //点击清除按钮时重置预测结果文本框

        digitClassifier.initialize()
        //分类器初始化

        drawView?.setOnTouchListener(){_, event ->
            drawView?.onTouchEvent(event)
            if(event.action == MotionEvent.ACTION_UP)
            {
                classifyDrawing()
                //手写区域有操作时进行手写数字识别
            }
            true
        }

    }

    override fun onDestroy() {
        digitClassifier.close()
        super.onDestroy()
    }
    //设置删除回收操作

    private fun classifyDrawing(){
        //进行手写数字识别

        val bitmap = drawView?.getBitmap()
        //获取手写区域的图像

        if ((bitmap != null) && (digitClassifier.isInitialized)) {
            //当手写区域非空且分类器已经初始化后
            predictedTextView?.text = "pass"
            digitClassifier
                .classifyAsync(bitmap)
                .addOnSuccessListener { resultText -> predictedTextView?.text = resultText }
                .addOnFailureListener { e-> predictedTextView?.text = e.localizedMessage.toString() }
                }
    }

    companion object{
        private const val TAG = "MainActivity"
    }
}